import React, { useState, useRef } from 'react';
import { UploadOutlined } from '@ant-design/icons';
import { Modal, Button, Upload, Form, Input, message, Select } from 'antd';
import {
  DataType,
  saveOrUpdateDishApi,
  saveOrUpdateDish,
  getDishPhotoAPI,
} from '@/service/dish';

interface DishProps {
  dishData: DataType;
  isUpdate?: boolean;
  fetchData: () => void; // 父组件传递的方法
}

const CreateOrUpdateDish: React.FC<DishProps> = ({
  dishData,
  isUpdate = false,
  fetchData,
}) => {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const formRef = useRef(null); // 创建一个引用到表单

  const data: saveOrUpdateDish = {
    restaurantId: 0,
    id: dishData?.id || '',
    image: '',
    name: '',
    price: 0,
    classify: 0,
    number: 0,
  };

  const options = [
    {
      value: '1',
      label: '未分类',
    },
    {
      value: '2',
      label: '热菜',
    },
    {
      value: '3',
      label: '凉菜',
    },
    {
      value: '4',
      label: '主食',
    },
    {
      value: '5',
      label: '汤类',
    },
    {
      value: '6',
      label: '饮品',
    },
    {
      value: '7',
      label: '甜品',
    },
    {
      value: '8',
      label: '其他',
    },
  ];

  const onFinish = async (values: any) => {
    const restaurantId = localStorage.restaurant;
    data.restaurantId = Number(restaurantId);
    data.name = values.name;
    data.price = values.price;
    data.classify = values.classify.value;
    data.number = values.number;
    if (isUpdate) {
      const path = await getDishPhotoAPI(dishData.id);
      data.image = path;
      await saveOrUpdateDishApi(data);
      message.success('更新成功');
    } else {
      await saveOrUpdateDishApi(data);
      message.success('创建成功');
    }
    setIsModalOpen(false);
    fetchData();
  };

  const handleUpload = async (info: any) => {
    if (info.file.status === 'uploading') {
      return;
    }
    if (info.file.status === 'done') {
      const file: File = info.file.originFileObj;
      const path = 'dish';
      try {
        const formData = new FormData();
        formData.append('file', file);
        await fetch(
          `http://localhost:10001/ftp/upload?path=${encodeURIComponent(path)}`,
          {
            method: 'POST',
            body: formData,
          },
        );
        data.image = file.name;
        message.success(`${info.file.name} 文件上传成功.`);
      } catch (error) {
        message.error(`${info.file.name} 文件上传失败.`);
      }
    }
  };

  const beforeUpload = (file: File) => {
    const isJpgOrPng =
      file.type === 'image/jpeg' || file.type === 'image/png' ? true : false;
    if (!isJpgOrPng) {
      message.error('只能上传 JPG/PNG 文件!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片必须小于 2MB!');
    }
    return isJpgOrPng && isLt2M;
  };

  const showModal = () => {
    setIsModalOpen(true);
  };

  const handleOk = () => {
    formRef.current.submit(); // 当点击"OK"时，提交表单
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  return (
    <>
      <Button type="primary" onClick={showModal}>
        {isUpdate ? '编辑' : '新建'}
      </Button>
      <Modal
        title={isUpdate ? '更新菜品' : '创建菜品'}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          autoComplete="off"
          ref={formRef} // 将引用添加到表单
        >
          <Form.Item<DataType>
            label="菜品名称"
            name="name"
            initialValue={isUpdate ? dishData.name : ''}
          >
            <Input defaultValue={isUpdate ? dishData.name : ''} />
          </Form.Item>
          <Form.Item<DataType>
            label="菜品价格"
            name="price"
            initialValue={isUpdate ? dishData.price : ''}
          >
            <Input value={isUpdate ? dishData.price : ''} />
          </Form.Item>
          <Form.Item<DataType>
            label="菜品分类"
            name="classify"
            initialValue={isUpdate ? options[dishData.classify] : ''}
          >
            <Select
              labelInValue
              value={
                isUpdate
                  ? {
                      value: dishData.classify,
                      label: options.find(
                        (item) => item.value === String(dishData.classify),
                      )?.label,
                    }
                  : { value: '1', label: '未分类' }
              }
              style={{ width: 120 }}
              options={options}
            />
          </Form.Item>
          <Form.Item<DataType>
            label="菜品数量"
            name="number"
            initialValue={isUpdate ? dishData.number : ''}
          >
            <Input value={isUpdate ? dishData.number : ''} />
          </Form.Item>
          <Form.Item label="菜品图片">
            <Upload
              onChange={handleUpload}
              maxCount={1}
              beforeUpload={beforeUpload}
            >
              <Button icon={<UploadOutlined />}>上传照片</Button>
            </Upload>
          </Form.Item>
          {/* <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Button type="primary" htmlType="submit">
              Submit
            </Button>
          </Form.Item> */}
        </Form>
      </Modal>
    </>
  );
};

export default CreateOrUpdateDish;
